package com.dysm.spring.security.service;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class MyUserService implements UserDetailsService, InitializingBean {

    private final List<UserDetails> userDetails = new ArrayList<>();

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userDetails.stream().filter(u -> Objects.equals(u.getUsername(), username)).findAny().orElse(null);
    }

    @Override
    public void afterPropertiesSet() {
        // role必须要以  ROLE_开头，否则请求时直接被拦截，返回403
        List<SimpleGrantedAuthority> adminAuthorities = Stream.of(new SimpleGrantedAuthority("ROLE_ADMIN"))
                .collect(Collectors.toList());
        List<SimpleGrantedAuthority> empAuthorities = Stream.of(new SimpleGrantedAuthority("ROLE_EMP"))
                .collect(Collectors.toList());
        String encode = bCryptPasswordEncoder.encode("123321");
        userDetails.add(new User("xiay", encode, adminAuthorities));
        userDetails.add(new User("zhangs", encode, empAuthorities));
        userDetails.add(new User("lis", encode, empAuthorities));
    }
}
